package arpc

import (
	"sync"
	"sync/atomic"
)

type Pool struct {
	pool   sync.Pool
	nalloc int32
	nfree  int32

	new func() any
}

func NewPool(new func() any) *Pool {
	return &Pool{
		pool: sync.Pool{},
		new:  new,
	}
}

func (p *Pool) Get() any {
	x := p.pool.Get()
	if x == nil {
		x = p.new()
		atomic.AddInt32(&p.nalloc, 1)
	} else {
		atomic.AddInt32(&p.nfree, -1)
	}

	return x
}

func (p *Pool) Put(x any) {
	p.pool.Put(x)
	atomic.AddInt32(&p.nfree, 1)
}

func (p *Pool) Resource() (int32, int32) {
	return p.nalloc, p.nfree
}
